package com.ajz.config;

import java.util.Map;

import javax.annotation.PostConstruct;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import com.ajz.common.exception.BusinessException;
import com.google.common.collect.Maps;

/**
 *  数据权限 配置类
 * @author sheng.han
 *
 */
@Component
public class DataPermissionConfiguration implements EnvironmentAware {

//	private static Logger log = LoggerFactory.getLogger(DataPermissionConfiguration.class);
	
	private RelaxedPropertyResolver checkFieldPropertyResolver;
	
	@Value("${ajz.dataPermission.whiteList}")
	private String whiteList;
	
	@Value("${ajz.dataPermission.allShopid}")
	private String allShopid;
	
	@Value("${ajz.dataPermission.areaIdCheckLength}")
	private Integer areaIdCheckLength;
		    
	@Value("${ajz.security.defaultUserPassword}")
	private String defaultUserPassword;
	
	
	private Map<String, Object> whiteMap = Maps.newHashMap();
	
	@PostConstruct
	public void init() {
		if (StringUtils.isNotEmpty(whiteList)) {
			String[] entities = whiteList.split(",");
			for(String entity : entities) {
				whiteMap.put(entity, entity);
			}
		}
	}
	
	@Override
	public void setEnvironment(Environment env) {
		this.checkFieldPropertyResolver = new RelaxedPropertyResolver(env, "ajz.dataPermission.checkField.");
		
	}
	
	public String getCheckField(Class<?> entity) {
		String checkField = checkFieldPropertyResolver.getProperty(entity.getSimpleName());
		if (StringUtils.isEmpty(checkField)) {
			throw new BusinessException(String.format("%s数据权限校验字段未配置", entity.getSimpleName()));
		}
		return checkField;
	} 

	public boolean isInWhiteList(Class<?> entity) {
		return whiteMap.containsKey(entity.getSimpleName());
	}

	public String getAllShopid() {
		return allShopid;
	}

	public Integer getAreaIdCheckLength() {
		return areaIdCheckLength;
	}

	public String getDefaultUserPassword() {
		return defaultUserPassword;
	}
	
	
}
